import Vue from "vue";
import axios from "axios";
import { Loading, Notification } from "element-ui";

//创建一个 axios 的实例。 使之系统所有的请求走这个实例
const timeout = 1000 * 600;
const instance = axios.create({
  timeout,
  withCredentials: true,
  crossDomain:true,
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    "Cache-Control": "no-cache", //请求禁用缓存
  },
});
let loadingInstance1;
/**
 * 请求拦截
 */
instance.interceptors.request.use(
  (config) => {
    // config.headers["token"] = Vue.cookie.get("token"); // 请求头带上token
    // XXX: get 请求会被浏览器缓存。 虽然设置了cache-control 禁用缓存（对这个配置项理解的还不是很透彻），
    // 所以这里再加一个  timestamp 时间戳。防止get 请求被缓存

    if (config.method === "get") {
      if (!config.params) {
        config.params = {};
      }
      config.params.timestamp = Date.now();
    } else {
      if (!config.data) {
        config.data = {};
      }
    }
    if (config.noToast !== true) {
      loadingInstance1 = Loading.service({
        fullscreen: true,
        text: "加载中...",
      });
    }

    return config;
  },
  (error) => {
    clearToast();
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
instance.interceptors.response.use(
  (response) => {
    clearToast();
    if (response.status === 200) {
      if(response.data.data===undefined){
        response.data={
          data:response.data,
        }
      }
      //成功
      return response.data.data;
    } else {
      Notification({
        type: "danger",
        duration: 1000,
        message: "系统繁忙，请稍微再试~",
      });
      return Promise.reject(response.data);
    }
  },
  (error) => {
    clearToast();
    Notification({
      type: "danger",
      duration: 1000,
      message: "系统繁忙，请稍微再试！！！",
    });
    return Promise.reject(error);
  }
);

function clearToast() {
  loadingInstance1 && loadingInstance1.close();
}

export default instance;
